<script setup lang="ts">
import type { OpenAcceptanceBill } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getOpenAcceptanceBillById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

interface Attachment {
  name: string
  url: string
}
type OpenAcceptanceBillTemp = OpenAcceptanceBill & {
  attachmentList?: Attachment[]
}
// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '开立承兑汇票详情',
    enablePullDownRefresh: true, // 启用下拉刷新
  },
})

const flowIdValue = ref('')
const idValue = ref('')
// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<OpenAcceptanceBillTemp | null>(null)
const errorMessage = ref('')
// 刷新状态
const refreshing = ref(false)

// 准备基本信息数据
const basicInfoList = computed<InfoItem[]>(() => [
  {
    label: '业务机构',
    value: businessData.value?.businessInstitutionName || '-',
    key: 'businessInstitutionName',
  },
  {
    label: '业务部门',
    value: businessData.value?.businessDepartmentName || '-',
    key: 'businessDepartmentName',
  },
  {
    label: '业务员',
    value: businessData.value?.salesmanName || '-',
    key: 'salesmanName',
  },
  {
    label: '制单人',
    value: businessData.value?.preparer || '-',
    key: 'preparer',
  },
  {
    label: '创建时间',
    value: businessData.value?.createTime || '-',
    key: 'createTime',
    type: 'datetime',
  },
  {
    label: '更新时间',
    value: businessData.value?.updateTime || '-',
    key: 'updateTime',
    type: 'datetime',
  },
])

// 准备汇票信息数据
const billInfoList = computed<InfoItem[]>(() => [
  {
    label: '业务编号',
    value: businessData.value?.bizNo || '-',
    key: 'bizNo',
  },
  {
    label: '票据类型',
    value: businessData.value?.billType_dictText || '-',
    key: 'billType_dictText',
  },
  {
    label: '票据号码',
    value: businessData.value?.billNumber || '-',
    key: 'billNumber',
  },
  {
    label: '票面金额',
    value: businessData.value?.faceAmount || '0',
    key: 'faceAmount',
    type: 'currency',
  },
  {
    label: '票据金额',
    value: businessData.value?.billAmount || '0',
    key: 'billAmount',
    type: 'currency',
  },
  {
    label: '出票日期',
    value: businessData.value?.issueDate || '-',
    key: 'issueDate',
  },
  {
    label: '到期日期',
    value: businessData.value?.maturityDate || '-',
    key: 'maturityDate',
  },
  {
    label: '出票人',
    value: businessData.value?.drawer || '-',
    key: 'drawer',
    forceMultiline: true,
  },
  {
    label: '收款人',
    value: businessData.value?.payee || '-',
    key: 'payee',
    forceMultiline: true,
  },
  {
    label: '备注',
    value: businessData.value?.remarks || '-',
    forceMultiline: true,
  },
])

// 准备状态信息数据
const statusInfoList = computed<InfoItem[]>(() => [
  {
    label: '审批状态',
    value: businessData.value?.approvalStatus || '-',
    key: 'approvalStatus',
    type: 'approval',
  },
  {
    label: '支付状态',
    value: getStatusText('paymentStatus', businessData.value?.paymentStatus),
    key: 'paymentStatus',
  },
  {
    label: '票据状态',
    value: getStatusText('billStatus', businessData.value?.billStatus),
    key: 'billStatus',
  },
  {
    label: '开票状态',
    value: getStatusText('invoicingStatus', businessData.value?.invoicingStatus),
    key: 'invoicingStatus',
  },
])

// 准备流程信息数据
const processInfoList = computed<InfoItem[]>(() => [
  {
    label: '流程实例ID',
    value: currentProcess.value?.id || '-',
    key: 'processId',
    forceMultiline: true,
  },
  {
    label: '流程名称',
    value: currentProcess.value?.name || '-',
    key: 'processName',
  },
])

// 根据附件列表显示
const attachmentInfoList = computed<InfoItem[]>(() => {
  let attachments: any[] = []

  // 先检查 attachmentList（新格式）
  if (businessData.value?.attachmentList) {
    attachments = Array.isArray(businessData.value.attachmentList) ? businessData.value.attachmentList : []
  }

  if (attachments.length === 0) {
    return []
  }

  return attachments.map((item: any) => {
    // 支持两种格式：{ fileName, fileUrl, fileId } 和 { name, url }
    const fileName = item.fileName || item.name || '-'
    const fileUrl = item.fileUrl || item.url || '-'
    const fileId = item.fileId || `file-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
    return {
      label: fileName,
      value: fileUrl,
      key: fileId,
      slot: 'attachment',
      forceMultiline: true,
    }
  })
})

// 获取业务详情数据
async function getBusinessData() {
  try {
    // 标记开始刷新
    refreshing.value = true
    // 第一步：获取流程实例数据
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 等待流程实例数据加载完成并获取businessKey
    if (currentProcess.value.businessKey) {
      const res = await getOpenAcceptanceBillById(currentProcess.value.businessKey)
      businessData.value = res.data || null
      if (businessData.value?.attachment) {
        try {
          // 解析附件字符串为数组
          businessData.value.attachmentList = JSON.parse(businessData.value.attachment) || []
        }
        catch (e) {
          businessData.value.attachmentList = []
          console.error('解析附件数据失败:', e)
        }
      }
    }
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
  }
  // 标记数据已加载
  refreshing.value = false
}

// 页面加载时获取数据
onLoad(async (e) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId || ''
  }
  if (e.id) {
    idValue.value = e.id || ''
  }
})
// 页面显示时刷新数据（避免重复请求）
onShow(async () => {
  if (idValue.value) {
    await getBusinessData()
  }
})
// 监听下拉刷新事件
onPullDownRefresh(async () => {
  await getBusinessData()
  uni.stopPullDownRefresh()
})

// 获取状态显示文本
function getStatusText(type: string, value?: number) {
  const statusMaps: Record<string, Record<number, string>> = {
    approvalStatus: {
      0: '待审批',
      1: '审批中',
      2: '已审批',
      3: '已拒绝',
      4: '已撤销',
    },
    paymentStatus: {
      0: '待支付',
      1: '支付中',
      2: '已支付',
      3: '支付失败',
      4: '已退款',
    },
    billStatus: {
      0: '正常',
      1: '已承兑',
      2: '已贴现',
      3: '已转让',
      4: '已到期',
      5: '已兑付',
      6: '已作废',
    },
    invoicingStatus: {
      0: '未开票',
      1: '开票中',
      2: '已开票',
      3: '开票失败',
    },
    splitStatus: {
      0: '未拆分',
      1: '拆分中',
      2: '已拆分',
    },
    isInvoiced: {
      0: '否',
      1: '是',
    },
  }

  if (value === undefined || value === null) {
    return '-'
  }

  return statusMaps[type]?.[value] || `未知状态(${value})`
}
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-message">
      <text>{{ errorMessage }}</text>
      <button class="retry-button" @click="getBusinessData()">
        重试
      </button>
    </view>
    <view class="px-20rpx py-15rpx">
      <!-- 汇票信息卡片 -->
      <DetailCard
        title="汇票信息"
        :info-list="billInfoList"
      />
      <!-- 状态信息卡片 -->
      <DetailCard
        title="状态信息"
        :info-list="statusInfoList"
      />

      <!-- 基本信息卡片 -->
      <DetailCard
        title="操作信息"
        :info-list="basicInfoList"
      />

      <!-- 流程信息卡片 -->
      <DetailCard
        title="流程信息"
        :info-list="processInfoList"
      />
      <!-- 附件信息卡片 -->
      <DetailCard
        title="附件信息"
        :info-list="attachmentInfoList"
      >
        <template #attachment="{ item }">
          <AttachmentItem
            :file="{
              name: item.label || '-',
              url: item.value || '-',
            }"
          />
        </template>
      </DetailCard>
    </view>
    <!-- 审批操作栏 -->
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style scoped>
.page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 刷新状态指示器 */
.refresh-indicator {
  background: linear-gradient(to bottom, #fff 0%, #f8f9fa 100%);
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.refresh-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}

.refresh-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid #e3e3e3;
  border-top: 3rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.refresh-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 错误提示 */
.error-message {
  background-color: #fff2f0;
  border: 1rpx solid #ffccc7;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.error-message text {
  color: #ff4d4f;
  font-size: 28rpx;
  flex: 1;
}

.retry-button {
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  min-width: 120rpx;
}

.retry-button:active {
  background-color: #d4380d;
}

/* 自定义备注样式 */
.custom-remark {
  display: flex;
  gap: 16rpx;
  background-color: #fff7e6;
  border: 1rpx solid #ffd591;
  border-radius: 8rpx;
  padding: 16rpx;
}

.remark-icon {
  font-size: 32rpx;
  flex-shrink: 0;
}

.remark-content {
  flex: 1;
}

.remark-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8rpx;
}

.remark-note {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
  margin-top: 12rpx;
  padding-top: 12rpx;
  border-top: 1rpx solid #ffd591;
}
</style>
